#include "app_mqtt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "log/log.h"

// MQTT客户端
MQTTClient client;
// 连接选项
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

// 接收到MQTT消息的回调函数
static int (*recv_callback)(char *json) = NULL;
// 发送MQTT消息的消息结构体
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

// 发送MQTT消息回调函数
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("MQTT消息发送成功!\n");
}

// 接收MQTT消息回调函数
// 返回值：1：成功 0：失败
static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0;
    if (recv_callback)
    {
        result = !recv_callback((char *)message->payload);
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

// 连接失败回调函数
static void connlost(void *context, char *cause)
{
    log_debug("连接断开,原因: %s !\n", cause);
}

/**
 * @brief 初始化MQTT
 *
 * @return int 初始化结果 0：成功 -1：失败
 */
int app_mqtt_init(void)
{
    // 创建MQTT客户端
    if ((MQTTClient_create(&client, ADDRESS, CLIENTID,
                           MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        log_debug("创建MQTT客户端失败\n");
        return -1;
    }

    // 设置回调函数
    if ((MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
    {
        log_debug("设置MQTT回调函数失败\n");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 连接服务器
    if ((MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log_debug("连接MQTT服务器失败\n");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 订阅主题
    if ((MQTTClient_subscribe(client, TOPIC_RTG, QOS)) != MQTTCLIENT_SUCCESS)
    {
        log_debug("订阅主题失败\n");
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }

    log_debug("初始化MQTT成功\n");

    return 0;
}

/**
 * @brief 反初始化MQTT
 *
 */
void app_mqtt_deinit(void)
{
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
    
    log_debug("注销MQTT成功\n");
}

/**
 * @brief 发送MQTT消息
 *
 * @param json json字符串
 * @return int 发送结果 0：成功 -1：失败
 */
int app_mqtt_sendMes(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;
    if ((MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL)) != MQTTCLIENT_SUCCESS)
    {
        printf("发送MQTT消息失败!\n");
        return -1;
    }
    return 0;
}

/**
 * @brief 接收到MQTT消息的回调函数
 *
 * @param callback 回调函数指针
 */
void app_mqtt_registerRecvCallback(int (*callback)(char *json))
{
    recv_callback = callback;
}
